package cn.deschen.biz.service.impl;

import cn.deschen.biz.domain.entity.Columns;
import cn.deschen.biz.mapper.InformationSchemaMapper;
import cn.deschen.biz.service.InformationSchemaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author hanbin_chen
 * @Description 表信息 服务实现类
 * @DateTime 2021/6/10
 * @Version V1.0.0
 */
@Service
@Slf4j
public class InformationSchemaServiceImpl implements InformationSchemaService {

    public static final String SEPARATOR = ":";
    @Autowired
    private InformationSchemaMapper schemaMapper;

    public static final Map<String, List<Columns>> schemaColumnMap = new ConcurrentHashMap<>(16);

    @Override
    public String listColumn(String tableSchema, String tableName, Integer ordinalPosition) {
        String key = tableSchema + SEPARATOR + tableName;
        List<Columns> columnList = schemaColumnMap.get(key);
        if (CollectionUtils.isEmpty(columnList)) {
            columnList = schemaMapper.listColumn(tableSchema, tableName);
            schemaColumnMap.put(key, columnList);
        }
        String columnName = "";
        for (Columns column : columnList) {
            if (column.getOrdinalPosition().equals(ordinalPosition)) {
                columnName = column.getColumnName();
                break;
            }
        }
        return columnName;
    }
}
